package com.littlec.sdk.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.NameValuePair;


import android.util.Log;

import com.cmcc.groupcontacts.MainApp;
import com.littlec.sdk.asynctask.GroupDelTask;
import com.littlec.sdk.asynctask.GroupTask;
import com.littlec.sdk.asynctask.GroupUpdateTask;
import com.littlec.sdk.entity.CMGroup;
import com.littlec.sdk.entity.CMMember;
import com.littlec.sdk.listener.CMGroupListener;
import com.littlec.sdk.utils.CMChatGlobalStorage;
import com.littlec.sdk.utils.CMChatListener;
import com.littlec.sdk.utils.MyLogger;
import com.yinhai.asynctask.AsyncTaskParam;
import com.yinhai.asynctask.DeleteGroupTask;
import com.yinhai.asynctask.InitGetUserGroupsTask;
import com.yinhai.asynctask.NameValueParam;
import com.yinhai.constant.UrlConstant;
import com.yinhai.model.IMUserGroup;
import com.yinhai.service.IMGroupServiceImpl;
import com.yinhai.service.IMUserGroupServiceImpl;

public class CMGroupManager {
	private MyLogger logger = MyLogger.getLogger("CMGroupManager");
	private static CMGroupManager instance = null;
	private ExecutorService executorService = Executors.newFixedThreadPool(5);
	private static IMGroupServiceImpl imGroupService = null;
	private static IMUserGroupServiceImpl userGroupService = null;
	public static Map<String, ArrayList<CMMember>> groupMembers = new HashMap<String, ArrayList<CMMember>>();

	public static CMGroupManager getInstance() {
		if (instance == null) {
			synchronized (CMGroupManager.class) {
				if (instance == null) {
					instance = new CMGroupManager();
				}
			}
		}
		return instance;
	}

	protected static IMGroupServiceImpl getImGroupService() {
		if (imGroupService == null) {
			synchronized (CMGroupManager.class) {
				if (imGroupService == null) {
					imGroupService = new IMGroupServiceImpl(
							MainApp.getContext());
				}
			}
		}
		return imGroupService;
	}

	protected static IMUserGroupServiceImpl getIMUserGroupService() {
		if (userGroupService == null) {
			synchronized (CMGroupManager.class) {
				if (userGroupService == null) {
					userGroupService = new IMUserGroupServiceImpl(
							MainApp.getContext());
				}
			}
		}
		return userGroupService;
	}

	public void destroy() {
		instance = null;
		imGroupService = null;
		userGroupService = null;
	}

	/**
	 * 从服务器初始化数据到客户端
	 * 
	 * @param listener
	 */
	public void initGroupListFromServer(
			CMChatListener.OnInitGroupListener listener) {
		InitGetUserGroupsTask task = new InitGetUserGroupsTask(
				MainApp.getContext(), listener);
		List<NameValuePair> postParam = new ArrayList<NameValuePair>();
		NameValueParam groupNamep = new NameValueParam();
		groupNamep.setName("user_phone");
		groupNamep.setValue(CMChatGlobalStorage.getInstance()
				.getmLoginUserName());
		postParam.add(groupNamep);
		AsyncTaskParam getInitGroup = new AsyncTaskParam(UrlConstant.LOCAL_URI
				+ UrlConstant.GET_USER_GROUPS);
		getInitGroup.setPostParam(postParam);
		task.execute(getInitGroup);
	}
	// 创建群
	public CMGroup createGroup(String groupName, String describe,
				String ownerNick, HashMap<String, String> memberNickMap,
				CMGroupListener.OnAddGroupListener addGroupListener) {
			String createUserPhone = CMChatGlobalStorage.getInstance()
					.getmLoginUserName();
			String createUserName = CMChatGlobalStorage.getInstance()
					.getmLoginUserRealName();
			StringBuffer sb = new StringBuffer();
			sb.append(createUserPhone);
			Iterator<String> iterator = memberNickMap.keySet().iterator();
			String key = "";
			while (iterator.hasNext()) {
				key = iterator.next();
				if(createUserPhone.equals(key)) {
					continue;
				}
				sb.append(",");
				sb.append(key);
			}
			List<NameValuePair> postParam = new ArrayList<NameValuePair>();
			NameValueParam groupNamep = new NameValueParam();
			groupNamep.setName("groupName");
			groupNamep.setValue(groupName);
			postParam.add(groupNamep);
			NameValueParam usersp = new NameValueParam();
			usersp.setName("users");
			usersp.setValue(sb.toString());
			postParam.add(usersp);
			NameValueParam createUserPhonep = new NameValueParam();
			createUserPhonep.setName("createUserPhone");
			createUserPhonep.setValue(createUserPhone);
			postParam.add(createUserPhonep);
			AsyncTaskParam addModifyGroup = new AsyncTaskParam(
					UrlConstant.LOCAL_URI + UrlConstant.ADD_MOD_GROUP);
			GroupTask groupTask = new GroupTask(MainApp.getContext(), groupName,
					createUserPhone, createUserName, memberNickMap,addGroupListener);
			addModifyGroup.setPostParam(postParam);
			
			groupTask.execute(addModifyGroup);
			return null;
		}
	public void getGroupListFromServer(CMChatListener.OnGroupListener listener) {
		List<CMGroup> paramList = new ArrayList<CMGroup>();
		// group_id id,group_name name,user_phone
		List<Map<String, String>> list = CMGroupManager.getImGroupService()
				.getGroup();
		CMGroup cmGroup = null;
		List<IMUserGroup> maps = null;
		try {
			for (int i = 0; i < list.size(); i++) {
				cmGroup = new CMGroup();
				String groupId = list.get(i).get("id");
				cmGroup.setGroupId(groupId);
				cmGroup.setGroupName(list.get(i).get("name") == null ? ""
						: list.get(i).get("name"));
				paramList.add(cmGroup);
			}
			listener.onSuccess(paramList);
		} catch (Exception e) {
			listener.onFailed("系统错误!" + e.getMessage());
		}
	}

	

	// 在群里需要 在群里需要 邀请其他人员时 邀请其他人员时 邀请其他人员时 邀请其他人员时 用
//	public List<CMMember> inviteMembersToGroup(String groupId,
//			HashMap<String, String> memberNickMap) {
//		return null;
//	}

	// 退群
//	public void exitGroup(String groupId) {
//
//	}

	// 获取群名称 获
	public String getGroupNamefromServer(String groupId) {
		List<Map<String,String>> groups = CMGroupManager.getImGroupService().getGroup(groupId);
		String name="";
		if(groups != null && groups.size() > 0) {
			Map<String,String> groupMap = groups.get(0);
			name = groupMap.get("name") == null?"":groupMap.get("name");
		}
		return name;
	}

	// 获取群成员 获
	public ArrayList<CMMember> getGroupMembersfromServer(String groupId) {
		ArrayList<CMMember> members = CMGroupManager.getInstance().groupMembers
				.get(groupId);
		CMMember cmMember = null;
		if (members == null) {
			members = new ArrayList<CMMember>();
			ArrayList<CMMember> membersTem = new ArrayList<CMMember>(); 
			List<Map<String, String>> group = CMGroupManager
					.getImGroupService().getGroup(groupId);
			if (group != null && group.size() > 0) {
				String groupCreatePhone = group.get(0).get("user_phone") == null ? ""
						: group.get(0).get("user_phone").toString();
				List<IMUserGroup> maps = CMGroupManager.getIMUserGroupService()
						.findByGroupId(groupId);
				IMUserGroup userGroup = null;
				for (int i = 0; i < maps.size(); i++) {
					userGroup = maps.get(i);
					cmMember = new CMMember(userGroup.getUserId(),
							userGroup.getUserName());
						if (userGroup.getUserId().equals(groupCreatePhone)) {
							members.add(cmMember);
						} else {
							membersTem.add(cmMember);
						}
				}
				members.addAll(membersTem);
			}
			
			CMGroupManager.getInstance().groupMembers.put(groupId, members);
		}
		return members;
	}

	// 修改群名称 修
//	public void changeGroupName(String groupId, String newGroupName) {
//
//	}
//
//	// 踢除 群成员 群
//	public void kickMemberFromGroup(String groupId, String kickedId) {
//
//	}

	public void deleteGroup(String groupId,CMGroupListener.OnAddGroupListener addGroupListener) {
		GroupDelTask deleteGroupTask = new GroupDelTask(MainApp.getContext(),groupId,addGroupListener);
		List<NameValuePair> postParam = new ArrayList<NameValuePair>();
		NameValueParam groupIdp = new NameValueParam();
		groupIdp.setName("group_id");
		groupIdp.setValue(groupId);
		postParam.add(groupIdp);
		AsyncTaskParam deleteGroup = new AsyncTaskParam(UrlConstant.LOCAL_URI
				+ UrlConstant.DELETE_GROUP);
		deleteGroup.setPostParam(postParam);
		deleteGroupTask.execute(deleteGroup);
	}
	
	public void modifyGroup(String groupId,String groupName,Map<String,String> memberMap,CMGroupListener.OnAddGroupListener addGroupListener) {
		ArrayList<CMMember> m = getGroupMembersfromServer(groupId);
		String createUserPhone = CMChatGlobalStorage.getInstance()
				.getmLoginUserName();
		String createUserName = CMChatGlobalStorage.getInstance()
				.getmLoginUserRealName();
		List<String> removeMembers = new ArrayList<String>();
		//删除自己数据
		memberMap.remove(createUserPhone);
		for(CMMember m1:m) {
			if(createUserPhone.equals(m1.getMemberId())) {
				continue;
			} else {
				if(memberMap.get(m1.getMemberId()) == null) {
					removeMembers.add(m1.getMemberId());
				}
			}
		}
		
		StringBuffer sb = new StringBuffer();
		sb.append(createUserPhone);
		Iterator<String> iterator = memberMap.keySet().iterator();
		String key = "";
		while (iterator.hasNext()) {
			key = iterator.next();
			if(createUserPhone.equals(key)) {
				continue;
			}
			sb.append(",");
			sb.append(key);
		}
		
		List<NameValuePair> postParam = new ArrayList<NameValuePair>();
		NameValueParam groupIdp = new NameValueParam();
		groupIdp.setName("groupId");
		groupIdp.setValue(groupId);
		postParam.add(groupIdp);
		
		NameValueParam groupNamep = new NameValueParam();
		groupNamep.setName("groupName");
		groupNamep.setValue(groupName);
		postParam.add(groupNamep);
		NameValueParam usersp = new NameValueParam();
		usersp.setName("users");
		usersp.setValue(sb.toString());
		postParam.add(usersp);
		NameValueParam createUserPhonep = new NameValueParam();
		createUserPhonep.setName("createUserPhone");
		createUserPhonep.setValue(createUserPhone);
		postParam.add(createUserPhonep);
		AsyncTaskParam addModifyGroup = new AsyncTaskParam(
				UrlConstant.LOCAL_URI + UrlConstant.ADD_MOD_GROUP);
		GroupUpdateTask groupTask = new GroupUpdateTask(MainApp.getContext(),groupId,groupName,createUserPhone,createUserName,memberMap,removeMembers,addGroupListener);
		addModifyGroup.setPostParam(postParam);
		groupTask.execute(addModifyGroup);
	}
}
